new Vue({
  el: '#app',
  data() {
    // 表单校验规则
    const validateTargetIds = (rule, value, callback) => {
      if (this.messageForm.target_type === 2 && (!value || value.length === 0)) {
        callback(new Error('请选择角色'));
      } else if (this.messageForm.target_type === 3 && (!value || value.length === 0)) {
        callback(new Error('请选择用户'));
      } else {
        callback();
      }
    };

    const validateNotificationType = (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('请选择至少一种通知类型'));
      } else {
        callback();
      }
    };

    const validateEffectiveTime = (rule, value, callback) => {
      if (!value || value.length !== 2) {
        callback(new Error('请选择生效时间范围'));
      } else {
        callback();
      }
    };

    return {
      isEdit: false,
      messageId: null,
      loading: false,
      activeLanguage: 'zh',
      editors: {},
      messageForm: {
        title: '',
        target_type: 1,
        role_ids: [],
        user_ids: [],
        notification_type: ['app_popup'],
        priority: 3,
        effective_time: [],
        status: 1,
        contents: {
          zh: { title: '', content: '', body: '' },
          en: { title: '', content: '', body: '' },
          km: { title: '', content: '', body: '' },
          fil: { title: '', content: '', body: '' }
        }
      },
      rules: {
        target_type: [{ required: true, message: '请选择通知人群', trigger: 'change' }],
        role_ids: [{ validator: validateTargetIds, trigger: 'change' }],
        user_ids: [{ validator: validateTargetIds, trigger: 'change' }],
        notification_type: [{ validator: validateNotificationType, trigger: 'change' }],
        priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
        effective_time: [{ validator: validateEffectiveTime, trigger: 'change' }],
        'contents.zh.title': [{ required: true, message: '请输入中文标题', trigger: 'blur' }],
        'contents.zh.content': [{ required: true, message: '请输入中文简短内容', trigger: 'blur' }],
        'contents.en.title': [{ required: true, message: '请输入英文标题', trigger: 'blur' }],
        'contents.en.content': [{ required: true, message: '请输入英文简短内容', trigger: 'blur' }],
        'contents.km.title': [{ required: true, message: '请输入柬埔寨语标题', trigger: 'blur' }],
        'contents.km.content': [{ required: true, message: '请输入柬埔寨语简短内容', trigger: 'blur' }],
        'contents.fil.title': [{ required: true, message: '请输入菲律宾语标题', trigger: 'blur' }],
        'contents.fil.content': [{ required: true, message: '请输入菲律宾语简短内容', trigger: 'blur' }]
      },
      roleOptions: [
        { value: 1, label: '管理员' },
        { value: 2, label: '运营' },
        { value: 3, label: '客服' },
        { value: 4, label: '普通用户' }
      ],
      userOptions: [],
      userLoading: false
    };
  },
  created() {
    // 获取URL参数，判断是新增还是编辑
    const urlParams = new URLSearchParams(window.location.search);
    this.messageId = urlParams.get('id');
    this.isEdit = !!this.messageId;

    if (this.isEdit) {
      this.fetchMessageDetail();
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initQuillEditors();
    });
  },
  watch: {
    activeLanguage(newVal, oldVal) {
      if (oldVal) {
        // 切换语言时保存富文本内容
        this.messageForm.contents[oldVal].body = this.editors[oldVal].root.innerHTML;
      }

      // 设置新语言的富文本内容
      this.$nextTick(() => {
        if (this.editors[newVal]) {
          this.editors[newVal].root.innerHTML = this.messageForm.contents[newVal].body || '';
        }
      });
    }
  },
  methods: {
    initQuillEditors() {
      const languages = ['zh', 'en', 'km', 'fil'];
      const toolbarOptions = [
        ['bold', 'italic', 'underline', 'strike'],
        ['blockquote', 'code-block'],
        [{ 'header': 1 }, { 'header': 2 }],
        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
        [{ 'script': 'sub'}, { 'script': 'super' }],
        [{ 'indent': '-1'}, { 'indent': '+1' }],
        [{ 'direction': 'rtl' }],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        ['clean'],
        ['link', 'image']
      ];

      languages.forEach(lang => {
        const editor = new Quill(`#editor-${lang}`, {
          modules: {
            toolbar: toolbarOptions
          },
          theme: 'snow'
        });

        this.editors[lang] = editor;

        // 设置初始内容
        if (this.messageForm.contents[lang].body) {
          editor.root.innerHTML = this.messageForm.contents[lang].body;
        }
      });
    },

    fetchMessageDetail() {
      this.loading = true;
      const url = `/api/admin/messages/${this.messageId}`;

      window.we.fetch(url)
      .then(data => {
        if (data.code === 0) {
          this.setFormData(data);
        } else {
          this.$message.error('获取消息详情失败');
        }
      })
      .catch(error => {
        console.error('获取消息详情出错:', error);
        this.$message.error('获取消息详情出错');
      })
      .finally(() => {
        this.loading = false;
      });
    },

    setFormData(data) {
      // 设置表单数据
      this.messageForm = {
        title: data.title,
        target_type: data.target_type,
        role_ids: data.role_ids || [],
        user_ids: data.user_ids || [],
        notification_type: data.notification_type || ['app_popup'],
        priority: data.priority,
        effective_time: [data.effective_start_at, data.effective_end_at],
        status: data.status,
        contents: {}
      };

      // 设置多语言内容
      const languages = ['zh', 'en', 'km', 'fil'];
      languages.forEach(lang => {
        const content = data.contents.find(item => item.language === lang) || {
          language: lang,
          title: '',
          content: '',
          body: ''
        };

        this.messageForm.contents[lang] = {
          title: content.title,
          content: content.content,
          body: content.body
        };
      });

      // 更新富文本编辑器内容
      this.$nextTick(() => {
        languages.forEach(lang => {
          if (this.editors[lang]) {
            this.editors[lang].root.innerHTML = this.messageForm.contents[lang].body || '';
          }
        });
      });
    },

    handleTargetTypeChange(value) {
      // 重置选择的角色和用户
      this.messageForm.role_ids = [];
      this.messageForm.user_ids = [];
    },

    remoteSearchUsers(query) {
      if (query === '') {
        this.userOptions = [];
        return;
      }

      this.userLoading = true;

      fetch('/api/admin/users', {
        method: 'GET',
        params: { keyword: query },
      })
      .then(data => {
        if (data.code === 0) {
          this.userOptions = data.data.map(item => ({
            value: item.id,
            label: item.username
          }));
        }
      })
      .catch(error => {
        console.error('搜索用户出错:', error);
      })
      .finally(() => {
        this.userLoading = false;
      });
    },

    submitForm() {
      // 保存当前语言的富文本内容逻辑保持不变...

      this.$refs.messageForm.validate(valid => {
        if (!valid) {
          this.$message.error('请完善表单信息');
          return;
        }

        const data = {
          // 构造提交数据逻辑保持不变...
        };

        let apiUrl = '/api/admin/messages';
        let options = {
          method: this.isEdit ? 'PUT' : 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        };

        if (this.isEdit) {
          apiUrl += `/${this.messageId}`;
        }

        window.we.fetch(apiUrl, options)
        .then(data => {
          if (data.code === 0) {
            this.$message({
              type: 'success',
              message: this.isEdit ? '修改成功' : '创建成功'
            });

            if (this.messageForm.status === 2) {
              this.goBack();
            } else {
              if (!this.isEdit) {
                this.isEdit = true;
                this.messageId = data.data.id;
                window.history.replaceState(null, '', `?id=${this.messageId}`);
              }
              this.loading = false;
            }
          } else {
            this.$message.error(data.message || '操作失败');
            this.loading = false;
          }
        })
        .catch(error => {
          console.error('提交表单出错:', error);
          this.$message.error('提交表单出错');
          this.loading = false;
        });
      });
    },

    goBack() {
      window.location.href = '/list.html';
    }
  }
});
